import React, { PropTypes, PureComponent } from 'react';
import { connect } from 'dva';
import { Form } from '@ant-design/compatible';
import '@ant-design/compatible/assets/index.css';
import { Row, Col, Input, Spin, Select, message } from 'antd';
import { NoDataC, TableC, SecondHeaderC, PrimaryC, FormItemLayout, ModalC, SecuritiesCodeC, codeType, SelectC } from '../../../comps';
import config from '../../../comps/business/tradingMarket/config';
import styles from '../index.less';

const FormItem = Form.Item;
@Form.create()
class AttentionTable extends PureComponent {
  state = {
    selectId: '', //选择查看组的id
    selectName: '', //选择查看组的名称
    selectType: '', //选择查看个券/主体组
    isBondTable: false, //是否为个券table
    nodata: false,
    isLoading: true,
    visibleModal: false,
    issuerList: [], //主体全称列表
    exchangeCode: '', //交易市场
    tradingCode: '', //证券代码
    tradingName: '',
    tradingMarket: '', //交易市场
    dataSource: [],
    columns: [],
  };

  componentDidMount() {
    this.setState({
      nodata: this.props.noTableData,
    });
  }

  UNSAFE_componentWillReceiveProps(nextProps) {
    //判断是否是最新的bondID

    if (nextProps.selectId && nextProps.selectId != this.state.selectId) {
      this.setState(
        {
          selectId: nextProps.selectId,
          selectName: nextProps.selectName,
          selectType: nextProps.selectType,
          isBondTable: nextProps.selectType == 'bond' ? true : false,
          isLoading: true,
        },
        () => {
          this.getTableData();
          this.getSelectList();
        },
      );
    } else {
      this.setState({
        nodata: nextProps.noTableData,
        isLoading: false,
      });
    }
  }
  //获取table数据
  getTableData = () => {
    const { isBondTable, selectId } = this.state;
    const { dispatch } = this.props;
    if (isBondTable) {
      //获取个券详情列表
      dispatch({
        type: 'myAttentionM/getBondInfoList',
        payload: {
          securityGroupId: selectId,
          currentPage: 1,
          numInPage: 500,
        },
        callback: (res) => {
          res.dataSource.map((item) => {
            let temp = config.filter((ele) => {
              return ele.value === item.exchangeCode;
            });
            if (temp && temp.length == 1) {
              item.exchangeCode = temp[0].title;
            }
          });
          this.setState({
            dataSource: res.dataSource,
            columns: res.columns,
            isLoading: false,
          });
        },
      });
    } else {
      //获取主体详情列表
      dispatch({
        type: 'myAttentionM/getMainInfoList',
        payload: {
          companyGroupId: selectId,
          currentPage: 1,
          numInPage: 500,
        },
        callback: (res) => {
          this.setState({
            dataSource: res.dataSource,
            columns: res.columns,
            isLoading: false,
          });
        },
      });
    }
  };

  //获取下拉列表
  getSelectList = (e) => {
    const { isBondTable } = this.state;
    let payload = {};
    if (!isBondTable) {
      //获取主体全称列表
      if (!!e) {
        payload = {
          name: e,
        };
      }
      this.props.dispatch({
        type: 'myAttentionM/getIssuerList',
        payload: payload,
        callback: (data) => {
          let tempArr = [];
          if (data && JSON.stringify(data) != '{}') {
            data.dataSource.map((item) => {
              tempArr.push({ value: item.value, title: item.title });
            });
            this.setState({
              issuerList: tempArr,
            });
          } else {
            this.setState({
              issuerList: [],
            });
          }
        },
      });
    }
  };

  //新增关注个券/主体btn
  addTableBtn = () => {
    this.setState({
      visibleModal: true,
    });
  };

  //证券代码选择事件
  getExchangeCode = (item) => {
    if (!!item) {
      let temp = config.filter((ele) => {
        return ele.value === item.exchangeCode;
      });
      this.setState({
        tradingMarket: temp[0].title,
        exchangeCode: item.exchangeCode,
        tradingCode: item.tradingCode,
        tradingName: item.secuabbr,
      });
    }
  };

  //显示新增弹窗
  showModel = () => {
    const {
      form: { getFieldDecorator, validateFields, resetFields },
      dispatch,
      currentUser,
      loading,
    } = this.props;
    const { isBondTable, selectId, exchangeCode, tradingCode, tradingName, issuerList } = this.state;
    const modalProps = {
      visible: this.state.visibleModal,
      onOk: () => {
        validateFields((err, values) => {
          if (!err) {
            if (isBondTable) {
              let selectList = [
                {
                  groupId: selectId,
                  tradingCode: tradingCode,
                  exchangeCode: exchangeCode,
                  tradingName: tradingName,
                },
              ];
              dispatch({
                type: 'myAttentionM/addBondAttention',
                payload: {
                  selectList: selectList,
                },
                callback: (res) => {
                  message.success('添加成功');
                  resetFields();
                  this.setState({
                    visibleModal: false,
                    isLoading: true,
                    tradingMarket: '',
                  });
                  this.getTableData();
                },
              });
            } else {
              const temp = issuerList.filter((item) => {
                return item.value == values.issuer;
              });
              dispatch({
                type: 'myAttentionM/addMainAttention',
                payload: {
                  groupId: selectId,
                  comcode: values.issuer,
                  comname: temp && temp.length == 1 ? temp[0].title : undefined,
                },
                callback: (res) => {
                  message.success('添加成功');
                  resetFields();
                  this.setState({
                    visibleModal: false,
                    isLoading: true,
                  });
                  this.getTableData();
                },
              });
            }
          }
        });
      },
      onCancel: () => {
        resetFields();
        this.setState({
          visibleModal: false,
          tradingMarket: '',
        });
      },
      title: this.state.isBondTable ? '新增个券' : '新增主体',
      className: styles.addModal,
      // height: this.state.isBondTable ? 130 : 36,//内容区域的高度
      width: 380,
      maskClosable: false, // 点击蒙层是否允许关闭
    };
    return (
      <div>
        {this.state.isBondTable ? (
          <ModalC {...modalProps}>
            <Spin spinning={loading.effects['myAttentionM/addBondAttention'] == true}>
              <Form>
                <Row>
                  <Col>
                    <FormItem {...FormItemLayout} label={'个券组'}>
                      {getFieldDecorator('name', {
                        initialValue: this.state.selectName,
                      })(<Input maxLength={20} disabled={true} />)}
                    </FormItem>
                  </Col>
                  <Col>
                    <SecuritiesCodeC
                      form={this.props.form}
                      dataIndex='code6'
                      codeType={codeType.all}
                      style={{ overflow: 'hidden' }}
                      onChange={(e) => this.getExchangeCode(e)}
                      rules={[{ required: true, message: '请选择代码!' }]}
                      positionBody={true}
                    />
                  </Col>
                  <Col>
                    <FormItem {...FormItemLayout} label={'交易市场'}>
                      {getFieldDecorator('exchangeCode', {
                        initialValue: this.state.tradingMarket,
                      })(<Input maxLength={20} disabled={true} />)}
                    </FormItem>
                  </Col>
                </Row>
              </Form>
            </Spin>
          </ModalC>
        ) : (
          <ModalC {...modalProps}>
            <Spin spinning={loading.effects['myAttentionM/addMainAttention'] == true}>
              <Form>
                <Row>
                  <Col>
                    <SelectC
                      dataIndex='issuer'
                      form={this.props.form}
                      title='主体全称'
                      rules={[{ required: true, message: '主体全称不能为空!' }]}
                      multiple={false}
                      filterOption={false}
                      onSearch={(e) => this.getSelectList(e)}
                      dataSource={issuerList}
                      positionBody={true}
                    />
                  </Col>
                </Row>
              </Form>
            </Spin>
          </ModalC>
        )}
      </div>
    );
  };

  //删除个券/主体
  deleteItem = (record) => {
    const { dispatch, currentUser } = this.props;
    const type = this.state.isBondTable ? 1 : 2;
    dispatch({
      type: 'myAttentionM/deleteAttention',
      payload: {
        type: type,
        id: record.id,
        groupId: this.state.selectId,
      },
      callback: (res) => {
        message.success('删除成功');
        this.setState({
          isLoading: true,
        });
        this.getTableData();
      },
    });
  };

  //个券/主体table
  bondTable = () => {
    const columns = this.state.columns;
    const dataSource = this.state.dataSource;
    if (columns && columns.length) {
      // 最后一列添加操作列
      if (columns[columns.length - 1].title != '操作' && this.props.isDefault === '0') {
        columns.push({
          title: '操作',
          dataIndex: 'operate',
          key: 'operate',
          type: 'operate',
          operates: [
            {
              title: '删除',
              onClick: (record) => this.deleteItem(record),
            },
          ],
        });
      }
      columns.map((item) => {
        item.width = this.state.isBondTable ? '25%' : '50%';
      });
    }
    return (
      <div style={{ marginTop: '5px' }}>
        <TableC dataSource={dataSource} columns={columns} hidePage={true} scroll={{ y: 'calc(100vh - 246px)' }} />
      </div>
    );
  };

  render() {
    return (
      <Spin spinning={this.state.isLoading}>
        {this.state.nodata ? (
          <div style={{ marginTop: '10px' }}>
            <NoDataC height='calc(100vh - 176px)' />
          </div>
        ) : (
          <div>
            <div style={{ marginTop: '12px', position: 'relative' }}>
              <SecondHeaderC
                title={this.props.selectName}
                Right={
                  this.props.isDefault === '0' ? (
                    <PrimaryC
                      onClick={() => {
                        this.addTableBtn();
                      }}
                      title='新增'
                    />
                  ) : null
                }
              />
            </div>
            {this.bondTable()}
            {this.showModel()}
          </div>
        )}
      </Spin>
    );
  }
}
export default connect(({ myAttentionM, userM: user, loading }) => ({ myAttentionM, currentUser: user.currentUser, loading }))(AttentionTable);
